#!/usr/bin/python

#from pyExcelerator import *

from optparse import OptionParser, Option

import sys
import os
import errno
import signal
import timeit
import subprocess

def do_usage():
    print """ Gigantea batch running script, created by ChenYang, @Gigantea project.
    
    gigantea_run.py <commnad> [Options]

Available commands:
    
    memstress         Running memory working set update programm.
    ab                Running ApacheBanch program.

More:

    --mthread     [Num. of mem. hogs]
    --msize       [Size of mem. area allocated for each mem. hogs]
    --timeout     [Timeout]
    --concur      [Concurrency]
    --requests    [Num. of ab requests]
    --url         [URL]
    """
def exe_command(cmd):

    pipe = os.popen(cmd, "r")
    res = pipe.readlines()
    pipe.close()

    return res

def mems_gen(argv, pfilter):

    msize = pfilter['msize']
    mthread = pfilter['mthread']
    timeout = pfilter['timeout']

    #print ("mthread: %s; msize: %s; timeout: %s sec" % mthread, msize, timeout)

    cmd = "stress --vm-keep --vm " + str(mthread) + " --vm-bytes " + str(msize) + " --timeout " + str(timeout)

    while (1):
        #os.system(cmd)
        exe_command(cmd)

def ab_running(argv, pfilter):
    concur = pfilter['concur']
    req = pfilter['req']
    url = pfilter['url']
    ab_cmd = 'ab -n %s -c %s %s | grep Transfer' %(concur, req, url)
    
    ab_nfile = 'ab-%s-%s.log' %(concur, req)
    if os.path.exists(ab_nfile):
        os.remove(ab_nfile)
    ab_file = open(ab_nfile, "a")

    start = timeit.default_timer()

    while(True):
        res = exe_command(ab_cmd)
        elapsed = (timeit.default_timer() - start)

        tx = res[0].split()[2].strip()

        #print >> ab_file, "%f\t%s" %(elapsed, tx)
        print >> ab_file, "%s\t%s" %(elapsed, tx)
        print "%s\t%s" %(elapsed, tx)

    ab_file.close()

def do_main(args, pfilter):
    command = args[0]
    param = args[1:]

    if command == 'memstress':
        mems_gen(param, pfilter)
    elif command  == 'ab':
        ab_running(param, pfilter)
    else:
        do_usage(param, pfilter)

def main():
    usage = """ Gigantea batch running script, created by ChenYang, @Gigantea project.
    
    gigantea_run.py <commnad> [Options]

Available commands:
    memstress         Running memory working set update programm.
    ab                Running ApacheBanch program.

More:

    --mthread     [Num. of mem. hogs]
    --msize       [Size of mem. area allocated for each mem. hogs]
    --timeout     [Timeout]
    --concur      [Concurrency]
    --requests    [Num. of ab requests]
    --url         [URL]
    """
    parser = OptionParser(usage)
    parser.add_option('-p', '--mthread', action = 'store', type = 'string', dest = 'mthread', default = True,
            help = """ num. of mem. hogs
            """
            )
    parser.add_option('-s', '--msize', action = 'store', type = 'string', dest = 'msize', default = True,
            help = """ size of mem. area allocated for each mem. hogs
            """
            )
    parser.add_option('-t', '--timeout', action = 'store', type = 'string', dest = 'timeout', default = True,
            help = """ timeout
            """
            )
    parser.add_option('-c', '--concurrent', action = 'store', type = 'string', dest = 'concur', default = True,
            help = """ number of multiple requests to perform at a time
            """
            )
    parser.add_option('-n', '--requests', action = 'store', type = 'string', dest = 'req', default = True,
            help = """ number of requests to perform for the benchmarking session
            """
            )
    parser.add_option('-u', '--url', action = 'store', type = 'string', dest = 'url', default = True,
            help = """ url for ab
            """
            )

    parser.set_default('timeout', '1')
    parser.set_default('msize', '256M')
    parser.set_default('mthread', '1')
    ###############
    parser.set_default('concur', '30')
    parser.set_default('req', '30')
    parser.set_default('url', 'http://localhost/')

    (options, args) = parser.parse_args(sys.argv)

    if len(args) < 2:
        do_usage()
        exit()
        #error("Wrong command parameters")
    else:
        pfilter = {}
        if options.mthread:
            pfilter['mthread'] = options.mthread
        if options.msize:
            pfilter['msize'] = options.msize
        if options.timeout:
            pfilter['timeout'] = options.timeout
        if options.concur:
            pfilter['concur'] = options.concur
        if options.req:
            pfilter['req'] = options.req
        if options.url:
            pfilter['url'] = options.url

    do_main(args[1:], pfilter)

if __name__ == "__main__":
    main()

